package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.ChargingRecord;
import com.woniu.service.ChargingRecordService;
import com.woniu.mapper.ChargingRecordMapper;
import com.woniu.util.ResponseData;
import com.woniu.util.SnowflakeIdGenerator;
import com.woniu.vo.ChargingRecordVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author Apricity
* @description 针对表【charging_record(充电记录表)】的数据库操作Service实现
* @createDate 2025-02-13 20:16:58
*/
@Service
public class ChargingRecordServiceImpl extends ServiceImpl<ChargingRecordMapper, ChargingRecord>
    implements ChargingRecordService {

    @Resource
    private ChargingRecordMapper chargingRecordMapper;

    @Override
    public List<ChargingRecordVO> getChargingRecordList(String keyword, Integer pageNum, Integer pageSize) {
        Page<ChargingRecordVO> page = new Page<>(pageNum, pageSize);
        List<ChargingRecordVO> records;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            records = chargingRecordMapper.queryChargingRecordByKeyword(keyword, page);
        } else {
            records = chargingRecordMapper.queryChargingRecordList(page);
        }
        
        return records;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addChargingRecord(ChargingRecord chargingRecord) {
        return chargingRecordMapper.insert(chargingRecord) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteChargingRecord(Long id) {
        return chargingRecordMapper.deleteById(id) > 0;
    }

    @Override
    public ResponseData<?> insertChargingRecord(ChargingRecord chargingRecord) {
        try {
            long snowId=new SnowflakeIdGenerator().nextId();
            chargingRecord.setOrderNumber(String.valueOf(snowId));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if (chargingRecordMapper.insertChargingRecord(chargingRecord) > 0) {
            return ResponseData.ok();
        } else {
            return ResponseData.fail(500,"插入失败");
        }
    }
}




